<?php

    namespace addons\zpwxsys\model;

    use think\Db;

    class User extends BaseModel
    {
        protected $autoWriteTimestamp = true;
//    protected $createTime = ;
        protected $name = 'zpwxsys_user';

        public function orders()
        {
            return $this->hasMany('Order', 'user_id', 'id');
        }

        public function address()
        {
            return $this->hasOne('UserAddress', 'user_id', 'id');
        }


        public function updateUser($param)
        {
            Db::startTrans();// 启动事务
            try {
                $this->allowField(true)->save($param, ['id' => $param['id']]);
                Db::commit();// 提交事务
                $data = array('status' => 0);
            } catch (\Exception $e) {
                Db::rollback();// 回滚事务
                $data = array('status' => 1);
            }

            return json_encode($data);
        }

        /**
         * 用户是否存在
         * 存在返回uid，不存在返回0
         */
        public static function getByOpenID($openid)
        {
            $user = User::where('openid', '=', $openid)->find();
            return $user;
        }

        public static function getByUserWhere($map)
        {
            $user = User::where($map)->find();
            if($user){
                if($user['avatarUrl']!='')
                {
                    $user['avatarUrl'] = cdnurl($user['avatarUrl'], true);
                }
                if($user['qrcode']!='')
                {
                    $user['qrcode'] = cdnurl($user['qrcode'], true);
                }
            }else{
                $user['avatarUrl'] = '';
                $user['nickname'] = '用户不存在';
            }
            return $user;
        }


        public static function getByUserlistWhere($map, $Nowpage, $limits, $od)
        {

            $userlist = user::where($map)->order($od)->select();


            return $userlist;
        }


          public function getLevelAgentList($map)
    {
            $list =  $this->alias ('u')
            ->field('u.id AS id,u.nickname AS name ,u.tel AS tel,u.create_time AS create_time,u.avatarUrl AS avatarUrl ')

            //->join('agent a', 'a.uid = u.id','left')
            ->where($map)
            ->order('u.create_time desc')
            ->select();
            $data['from'] = 1;
            if($list)
            {
                foreach ($list as $k=>$v)
                {

                   if($v['name'] == '')
                   {

                        $list[$k]['name']='新用户';
                   }

                   $list[$k]['avatarUrl'] =  self::prefixImgUrl($v['avatarUrl'],$data);
                }
            }

            return $list;

    }



    }
